package com.jchen.elasticsearch.util;

import cn.hutool.core.lang.Assert;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;
import com.github.pagehelper.PageInfo;

import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author liyang
 * @date 2022/3/9 10:03
 */
public class EsPageUtil {

    private static final int MAX_RESULT_WINDOW = 10000;

    /**
     * 检测分页是否过大
     * @param pageNum 当前页
     * @param pageSize 页大小
     */
    public static void checkMaxResult(Integer pageNum, Integer pageSize) {
        int num = null == pageNum || pageNum <= 0 ? 1 : pageNum;
        int size = null == pageSize || pageSize <= 0 ? 10 : pageSize;
        int from = (num - 1) * size;
        Assert.state((from + size) <= MAX_RESULT_WINDOW, "分页查询过大，请使用条件过滤");
    }

    /**
     * 查询结果转换为PageInfo分页对象
     * @param pageNum 当前页
     * @param pageSize 页大小
     * @param searchResponse 查询结果
     * @param <T>
     * @return
     */
    public static <T> PageInfo<T> convertToPageInfo(Integer pageNum, Integer pageSize, SearchResponse<T> searchResponse) {
        assert searchResponse.hits().total() != null;
        long total = searchResponse.hits().total().value();
        List<T> esList = searchResponse.hits().hits().stream().map(Hit::source).collect(Collectors.toList());
        return convertToPageInfo(pageNum, pageSize, total, esList);
    }

    public static <T> PageInfo<T> convertToPageInfo(Integer pageNum, Integer pageSize, long total, List<T> list) {
        PageInfo<T> pageInfo = new PageInfo<>();
        // es默认pageNum=1,pageSize=10
        int pageNumTmp = null == pageNum ? 1 : pageNum;
        int pageSizeTmp = null == pageSize ? 10 : pageSize;
        pageInfo.setPageNum(pageNumTmp);
        pageInfo.setPageSize(pageSizeTmp);
        pageInfo.setTotal(total);
        pageInfo.setList(list);
        pageInfo.setSize(list.size());
        pageInfo.setStartRow((pageNumTmp - 1) * pageNumTmp + 1);
        pageInfo.setEndRow((pageNumTmp - 1) * pageNumTmp + list.size());
        pageInfo.setPages((int) (total % pageSizeTmp == 0 ? total / pageSizeTmp : total / pageSizeTmp + 1));
        return pageInfo;
    }
}
